package pvt_chat

import (
	"encoding/json"
	"errors"
	"github.com/olivere/elastic/v7"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/im"
	"longmen/server/internal/rpc/tencentim/messages/private_chat"
	"longmen/server/pkg/common/lib/bytesconv"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

// CustomerSendRequest 后台客服发言
type CustomerSendRequest struct {
	messages2.IncomingMessage
	Content  string `json:"content"`   // 发送内容
	UserId   string `json:"user_id"`   // 用户ID
	SenderId string `json:"sender_id"` // 客服ID
	ImgUrl   string `json:"img_url"`   // 图片
}

type BatchCustomerSendRequest struct {
	Session  *im.Conversation
	UserId   int
	AnchorId int
}

// CustomReply 后台主动发消息单条
func CustomReply(req CustomerSendRequest, sess *im.Conversation) error {
	content, _ := cache.AesEncrypt(req.Content)
	t := ""
	id := ""
	anchorInfo, err := cache.GetUserFullInfo(cast.ToInt(sess.AnchorId))
	if err != nil {
		return errors.New("主播信息错误！")
	}
	if req.Content == "admin_revoke" {
		t = messages2.PrivateMessageRevokeType
	} else {
		t = messages2.PrivateMessageReplyType
		writeOk := false
		id, writeOk = History{
			SessionId:  sess.ConversationId,
			SenderUid:  req.SenderId,
			SenderTag:  CustomSender,
			ReceiveUid: req.UserId,
			Content:    req.Content,
			ImgUrl:     req.ImgUrl,
			SendTime:   time.Now().UnixMilli(),
		}.WriteToEs()
		if !writeOk {
			return errors.New("写入ES错误！")
		}
	}
	message := private_chat.CSReplyMessage{
		IncomingMessage: messages2.IncomingMessage{Type: &t, GroupId: cast.ToInt(sess.AnchorId)},
		Content:         content,
		AnchorAvatar:    anchorInfo.Avatar,
		AnchorNickname:  anchorInfo.NickName,
		SendTime:        time.Now().UnixMilli(),
		ImgUrl:          req.ImgUrl,
		Id:              id,
	}
	marshal, _ := json.Marshal(message)
	return imsdk.GetSdk().SendUser(req.UserId, bytesconv.BytesToString(marshal))
}

// CustomReply 后台主动发消息批量
func BatchCustomReply(content string, sessions map[int][]*BatchCustomerSendRequest) error {
	enContent, err := cache.AesEncrypt(content)
	if err != nil {
		global.Log.Errorf("AesEncrypt err:%v", err)
	}
	t := messages2.PrivateMessageReplyType
	for anchorId, session := range sessions {
		anchorInfo, err := cache.GetUserFullInfo(anchorId)
		if err != nil {
			global.Log.Errorf("主播信息错误！")
			continue
		}
		message := private_chat.CSReplyMessage{
			IncomingMessage: messages2.IncomingMessage{Type: &t, GroupId: anchorId},
			Content:         enContent,
			AnchorAvatar:    anchorInfo.Avatar,
			AnchorNickname:  anchorInfo.NickName,
			SendTime:        time.Now().UnixMilli(),
		}
		marshal, _ := json.Marshal(message)
		var uids []string
		records := make([]*elastic.BulkIndexRequest, 0)
		for _, v := range session {
			uids = append(uids, cast.ToString(v.UserId))
			resp := History{
				SessionId:  v.Session.ConversationId,
				SenderUid:  cast.ToString(anchorId),
				SenderTag:  CustomSender,
				ReceiveUid: cast.ToString(v.UserId),
				Content:    content,
				SendTime:   time.Now().UnixMilli(),
			}
			records = append(
				records,
				elastic.NewBulkIndexRequest().Index(PrivateChatHistoryIndexName).Doc(resp),
			)
		}
		BatchWriteToEs(records)
		imsdk.GetSdk().BatchSendUser(uids, bytesconv.BytesToString(marshal))
	}

	return nil
}
